import React, { Component, PropTypes } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  ScrollView,
  DeviceEventEmitter,
  Platform,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Request from '../../../utils/request';
import NavCon from '../../Public/NavCon';
import Loading from '../../Public/Loading';
// import ErrorLoadPage from '../../Public/ErrorLoadPage';
import PxToDp from '../../../utils/PxToDp';
import Base from '../../../utils/Base';
import UserBaseInfo from '../../../containers/UserBaseInfoContainer';
import VehicleVisited from './VehicleVisited';
import ModalExt from '../../Public/ModalExt';
import FontFamilys from '../../../utils/FontFamilys';
import CommunicationOnline from '../../../containers/CommunicateContainer';
import { fetchDetail, fetchMoreVisit } from '../../../actions/MyCustomerDetailAction';
import { fetchSaleList, fetchMyCustomerList } from '../../../actions/SaleListActions';
import UserStageBtn from '../../../containers/UserStageContainer';
import { fetchLockUser } from '../../../actions/communicateAction';

const { width } = Base.window;
/* global detailWs */
/* global homeWS_URL */
/* global detailWs */
global.detailWs = null;
let stageNum = '';

class Details extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalShow: false,
      claimVisible: false,
      claim: false,
      onlineState: '',
      offlineState: '',
      loadErr: false,
    };
  }
  static propTypes = {
    dispatch: PropTypes.func,
  };
  _goBack() {
    const { dispatch } = this.props;
    this.props.navigator.pop();
    if (this.state.claim) {
      dispatch(fetchSaleList(1, true, false, 1, 0, 0, 0, 0));
    }
  }

  _goVehicleVisited(user, userType, car) {
    const { dispatch, data } = this.props;
    this.props.navigator.push({
      component: VehicleVisited,
      passProps: { user, userType, car, dispatch, data },
    });
  }

  _goCommunicationOnline(user) {
    const { dispatch } = this.props;
    if (detailWs) {
      detailWs.send(JSON.stringify({ uid: user.id }));
    }
    this.props.dispatch(fetchLockUser(user.id, (data) => {
      if (data && data.lock) {
        this.props.navigator.push({
          component: CommunicationOnline,
          passProps: { user, dispatch },
        });
      } else {
        DeviceEventEmitter.emit('showToast', data.err);
      }
    }));
  }

  _setModalVisible(visible) {
    this.setState({ modalShow: visible });
  }

  /**
  *认领客户
  */
  _claimRequest() {
    const userId = this.props ? this.props.user ? this.props.user.id : null : null;
    this._claimModalVisible(false);
    Request.get({
      url: `/dealer/user_claim/${userId}`,
      success: (data) => {
        if (data.ok === 1) {
          this.setState({ claim: true });
          DeviceEventEmitter.emit('showToast', '认领客户成功!');
          this.props.dispatch(fetchMyCustomerList(1, true, false, 1, 0, 0, 0, 0, 1, 0, 0,
            0, 0, 0, 0, 0, 0, ''));
        } else if (data.ok === 0) {
          DeviceEventEmitter.emit('showToast', data.msg);
        }
      },
      fail: () => {
        DeviceEventEmitter.emit('showToast', '认领客户失败!');
      },
      error: () => {
        DeviceEventEmitter.emit('showToast', '认领客户失败!');
      },
    });
  }

  _claimModalVisible(visible) {
    if (!this.state.claim) {
      this.setState({ claimVisible: visible });
    }
  }


  componentDidMount() {
    const { dispatch, id } = this.props;
    dispatch(fetchDetail(id, (data) => {
      if (data && data.err) {
        this.setState({ loadErr: true });
        console.log(this.state.loadErr);
      }
    }));
    dispatch(fetchMoreVisit(id));
    this._HomeOpen();
  }
  componentWillUnmount() {
    this._closeWs();
  }
  _closeWs() {
    if (detailWs) {
      detailWs.close();
      detailWs = null;
    }
  }

  _HomeOpen() {
    detailWs = new WebSocket(homeWS_URL);

    detailWs.onopen = (e) => {
      console.log('open', e);
    };
    // 返回
    detailWs.onmessage = (e) => {
      const $this = this;
      console.log('onmessage: ', e);
      if (e.type === 'message') {
        if (e.data[0] === '{') {
          const data = JSON.parse(e.data);
          if (data.offline) {
            $this.setState({ offlineState: data.offline.id });
            $this.setState({ onlineState: '' });
          } else if (data.online) {
            $this.setState({ onlineState: data.online.uid });
            $this.setState({ offlineState: '' });
          }
        }
      }
    };

    detailWs.onerror = (e) => {
      console.log('websocket onerror', e);
    };

    detailWs.onclose = (e) => {
      console.log('websocket onclose', e.code, e.reason);
    };
  }

  render() {
    const { data, dispatch, id, userType, user } = this.props;
    let online = user ? user.online : null;
    const titles = {
      saleChance: '销售机会详情',
      myCustomer: '我的客户详情',
      otherCustomer: '他人客户详情',
      otherChannel: '其他渠道用户详情',
    };
    const title = titles[userType];
    if (this.state.offlineState && id && id === this.state.offlineState) {
      online = false;
    }
    if (this.state.onlineState && id && id === this.state.onlineState) {
      online = true;
    }
    const color = online ? '#fff' : '#dddddd';
    const voiceIcon = online ? require('../../../img/home/invalidName.png') : require('../../../img/home/hVoiceDeft.png');
    const bgColor = online ? '#2be79b' : '#fff';

    if (user.stage) {
      stageNum = user.stage;
    }
    if (this.props.stageObj) {
      stageNum = this.props.stageObj;
    }

    return (
      <View style={[styles.flex, styles.bg, styles.titleTop]}>
        <NavCon
          currentTitle={title}
          bgColor="#fff"
          onPress={() => this._goBack()}
        />
        {
          data.user
          ?
            <ScrollView>
              <View style={styles.padding}>
                <View style={[styles.row, styles.between]}>
                  <Text style={styles.userInfo}>基本信息</Text>
                  <Text style={styles.source}>来源：移动数字经销店</Text>
                </View>
                <UserBaseInfo
                  navigator={this.props.navigator}
                  dispatch={this.props.dispatch}
                  data={data}
                  user={user}
                  id={id}
                  userType={userType}
                />

                <View style={[styles.carTitleV, styles.row]}>
                  <Text style={[styles.userInfo]}>看车详情</Text>
                  <View>
                    <Text style={styles.total}>{data.cars && data.cars.length > 0 ? `共${data.cars.length}页` : ''}</Text>
                  </View>
                </View>

                <View style={styles.carView}>
                  <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                    {
                            data.cars
                            ?
                              data.cars.map(car => (
                                <TouchableOpacity
                                  key={car.car_id}
                                  style={styles.carScroll}
                                  activeOpacity={0.6}
                                  onPress={() => this._goVehicleVisited(user, userType, car)}
                                >
                                  <LinearGradient
                                    colors={['#7b6aff', '#4cbbff']}
                                    style={styles.carLiner}
                                    start={{ x: 0, y: 1 }}
                                    end={{ x: 1, y: 1 }}
                                  >

                                    <View style={[styles.row, styles.linerTop]}>
                                      <View style={styles.row}>
                                        <View style={styles.Cicle} />
                                        <Image style={styles.carIcon} source={require('../../../img/home/hStoreicon.png')} />
                                      </View>
                                      <View style={styles.row}>
                                        <Image style={styles.timeIcon} source={require('../../../img/detail/dtTime.png')} />
                                        <Text style={[styles.carTimeT, styles.size16]}>
                                          {car.totaltime}
                                        </Text>
                                        <Text style={[styles.timeUnit, styles.size16]}>分</Text>
                                      </View>
                                    </View>
                                    <Text style={[styles.size16, styles.carItem]}>
                                      {car.carname}
                                    </Text>
                                    <Text style={styles.storeT}>
                                      {car.bill && car.bill.pickplace}
                                    </Text>
                                  </LinearGradient>
                                </TouchableOpacity>
                              ))
                            :
                             null
                          }

                  </ScrollView>
                </View>
              </View>
            </ScrollView>
        :
            <View style={styles.load}>
              <Loading />
            </View>
        }
        {
           userType === 'otherCustomer' || !data.user
           ?
           null
           :
           <View style={[{ marginTop: PxToDp(20) }, styles.row, styles.bottomSection]}>
             {
                userType === 'myCustomer' ?
                  <View style={[styles.bottomRow]}>
                    <TouchableOpacity

                      activeOpacity={0.6}
                      onPress={() => this._setModalVisible(true)}
                    >
                      <View style={[styles.userStage, styles.row]}>
                        <Image source={require('../../../img/home/invalidNameCliam.png')} />
                        <Text style={{ fontSize: PxToDp(14), color: '#8b8c8e' }}>客户阶段</Text>
                      </View>
                    </TouchableOpacity>
                    <View style={styles.lineR} />
                    <TouchableOpacity
                      disabled={!online}
                      activeOpacity={0.6}
                      onPress={() => this._goCommunicationOnline(user)}
                    >
                      <View
                        style={[styles.communicateOnline,
                          { backgroundColor: bgColor }]}
                      >
                        <Image source={voiceIcon} />
                        <Text style={{ fontSize: PxToDp(14), color }}>在线沟通</Text>
                      </View>
                    </TouchableOpacity>

                  </View> :
                  <View style={[styles.bottomRow]}>
                    <TouchableOpacity
                      activeOpacity={0.6}
                      onPress={() => this._claimModalVisible(true)}
                    >
                      <View style={[styles.userStage, styles.row]}>
                        <Image source={require('../../../img/home/invalidNameCliam.png')} />
                        <Text style={{ fontSize: PxToDp(14), color: '#8b8c8e' }}>认领客户</Text>
                      </View>
                    </TouchableOpacity>
                    <View style={styles.lineR} />
                    <TouchableOpacity
                      disabled={!online}
                      activeOpacity={0.6}
                      onPress={() => this._goCommunicationOnline(user)}
                    >
                      <View
                        style={[styles.communicateOnline,
                  { backgroundColor: bgColor }]}
                      >
                        <Image source={voiceIcon} />
                        <Text style={{ fontSize: PxToDp(14), color }}>在线沟通</Text>
                      </View>
                    </TouchableOpacity>

                  </View>
            }
           </View>
        }

        <ModalExt
          onRequestClose={() => this._setModalVisible(false)}
          animationType={'slide'}
          transparent
          visible={this.state.modalShow}
          onPress={() => this._setModalVisible(false)}
        >
          <UserStageBtn
            Comfirm={() => {
              this._setModalVisible(false);
            }}
            stageNum={stageNum}
            userId={id}
            dispatch={dispatch}
          />
        </ModalExt>
        <ModalExt
          style={styles.flex}
          animationType={'slide'}
          transparent
          onRequestClose={() => this._claimModalVisible(false)}
          visible={this.state.claimVisible}
          onPress={() => this._claimModalVisible(false)}
        >

          <View style={[styles.bgColor, styles.flex]}>
            <LinearGradient
              colors={['#7b6aff', '#4cbbff']}
              style={styles.linerModal}
              start={{ x: 0, y: 1 }}
              end={{ x: 1, y: 1 }}
            >
              <View style={[styles.row, styles.linerTitle]}>
                <View style={styles.lineL} />
                <Text style={styles.climT}>认领客户</Text>
                <View style={styles.lineL} />
              </View>

              <View style={styles.climCon}>
                <Text style={styles.climConT}>
                成功认领后该客户将成为您的私属
              </Text>
                <Text style={styles.climConT}>
                客户，即可查阅客户联系方式
              </Text>
              </View>
            </LinearGradient>
            <View style={styles.climBottm}>
              <TouchableOpacity
                activeOpacity={0.6}
                style={styles.climBtn}
                onPress={() => this._claimRequest()}
              >
                <Text style={styles.commitT}>认领客户</Text>
              </TouchableOpacity>
            </View>
          </View>


        </ModalExt>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  flex: {
    flex: 1,
  },
  bg: {
    backgroundColor: '#f7f8fa',
  },
  row: {
    flexDirection: 'row',
  },
  padding: {
    paddingTop: PxToDp(20),
  },
  between: {
    justifyContent: 'space-between',
  },
  userInfo: {
    color: '#121212',
    fontSize: PxToDp(18),
    fontWeight: 'bold',
    marginLeft: PxToDp(21),
  },
  source: {
    color: '#999',
    fontSize: PxToDp(12),
    marginRight: PxToDp(20),
    marginTop: PxToDp(5),
  },
  bottomSection: {
    justifyContent: 'flex-end',
    paddingTop: PxToDp(10),
    paddingBottom: PxToDp(10),
    backgroundColor: '#fff',
    borderStyle: 'solid',
    borderColor: '#e4e5f4',
    borderTopWidth: PxToDp(1),
  },
  communicateOnline: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: PxToDp(12),
    width: PxToDp(100),
    height: PxToDp(30),
    backgroundColor: '#667aff',
    borderRadius: PxToDp(100),
    marginLeft: PxToDp(16),
  },
  userStage: {
    height: PxToDp(30),
    alignItems: 'center',
  },
  bottomRow: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    width: '100%',
  },
  bgColor: {
    backgroundColor: 'transparent',
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: '#F65252',
  },
  titleTop: {
    marginTop: Platform.OS === 'ios' ? 20 : 0,
  },
  carItem: {
    backgroundColor: 'transparent',
    marginTop: PxToDp(28),
    marginLeft: PxToDp(15),
  },
  lineR: {
    backgroundColor: '#e4e4e4',
    height: PxToDp(15),
    width: PxToDp(1),
    marginLeft: PxToDp(16),
    marginTop: PxToDp(8),
  },
  load: {
    height: PxToDp(500),
    alignItems: 'center',
    justifyContent: 'center',
  },
  carView: {
    paddingLeft: PxToDp(20),
  },
  carScroll: {
    marginTop: PxToDp(6),
    width: width - 40,
    height: PxToDp(140),
    marginRight: PxToDp(10),
  },
  carLiner: {
    height: '100%',
    borderRadius: PxToDp(2),
  },
  carTitleV: {
    marginTop: PxToDp(20),
    paddingRight: PxToDp(20),
    justifyContent: 'space-between',
  },
  total: {
    fontFamily: FontFamilys(),
    fontSize: PxToDp(12),
    color: '#8b8c8e',
  },
  Cicle: {
    height: PxToDp(8),
    width: PxToDp(8),
    backgroundColor: '#FFF',
    borderRadius: PxToDp(5),
    marginTop: PxToDp(32),
  },
  carIcon: {
    marginTop: PxToDp(27),
    marginLeft: PxToDp(9),
  },
  timeIcon: {
    marginTop: PxToDp(26),
  },
  carTimeT: {
    backgroundColor: 'transparent',
    marginLeft: PxToDp(6),
    marginRight: PxToDp(7),
    marginTop: PxToDp(22),
    fontWeight: 'bold',
  },
  timeUnit: {
    marginTop: PxToDp(21),
    backgroundColor: 'transparent',
  },
  size16: {
    color: '#ffffff',
    fontSize: PxToDp(16),
    fontFamily: FontFamilys(),
  },
  linerTop: {
    paddingRight: PxToDp(15),
    justifyContent: 'space-between',
    height: PxToDp(44),
    paddingLeft: PxToDp(21),
  },
  storeT: {
    fontSize: PxToDp(12),
    color: '#c4d2ff',
    fontFamily: FontFamilys(),
    marginTop: PxToDp(4),
    backgroundColor: 'transparent',
    marginLeft: PxToDp(20),
  },
  linerModal: {
    width: PxToDp(285),
    height: PxToDp(176),
    paddingTop: PxToDp(21),
  },
  linerTitle: {
    height: PxToDp(22),
    alignItems: 'center',
    paddingLeft: PxToDp(18),
    paddingRight: PxToDp(18),
  },
  climT: {
    color: '#ffffff',
    fontFamily: FontFamilys(),
    fontSize: PxToDp(16),
    backgroundColor: 'transparent',
    marginLeft: PxToDp(12),
    marginRight: PxToDp(12),
  },
  lineL: {
    width: PxToDp(80),
    backgroundColor: '#a5c9ec',
    height: PxToDp(1),
  },
  climConT: {
    color: '#c4d2ff',
    fontSize: PxToDp(14),
    fontFamily: FontFamilys(),
    backgroundColor: 'transparent',
  },
  climCon: {
    alignItems: 'center',
    marginTop: PxToDp(35),
  },
  climBottm: {
    height: PxToDp(86),
    width: PxToDp(285),
    backgroundColor: '#FFF',
    alignItems: 'center',
    justifyContent: 'center',
  },
  climBtn: {
    width: PxToDp(152),
    height: PxToDp(38),
    borderRadius: PxToDp(100),
    borderStyle: 'solid',
    borderColor: '#458fff',
    borderWidth: PxToDp(1),
    alignItems: 'center',
    justifyContent: 'center',
  },
  commitT: {
    color: '#458fff',
    fontSize: PxToDp(16),
    fontFamily: FontFamilys(),
  },
});

export default Details;
